<template>
    <section style="padding:20px"  v-loading="formLoading">
        <!-- 上传 -->
        <input
                type="file"
                accept=".xlsx,.xls,.csv"
                @change="handleImport"
        />
        <el-button
                type="primary"
                style="margin-left:12px"
                :disabled="!workbook"
                @click="handleCreate"
        >
            生成数据
        </el-button>
        <el-button
                type="primary"
                style="margin-left:12px"
                :disabled="!workbook"
                @click="handleExport"
        >
            导出全部 Sheet
        </el-button>
        <div class="" @click="copyToClipboard()" style="color: #409EFF;">
            随机数模版
        </div>
        <!-- 多页签 -->
        <el-tabs v-model="activeName" style="margin-top:20px">
            <el-tab-pane
                    v-for="(sheet, name) in sheets"
                    :key="name"
                    :label="name"
                    :name="name"
            >
                <el-table
                        :data="sheet.data"
                        border
                        max-height="600"
                        style="width:100%"
                >
                    <el-table-column
                            v-for="col in sheet.columns"
                            :key="col"
                            :prop="col"
                            :label="col"
                    >
                        <template #default="{ row, $index }">
                            <el-input
                                    v-model="sheet.data[$index][col]"
                                    size="small"
                            />
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
    </section>
</template>

<script setup>
import { ref } from 'vue'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'
import { ElMessage } from 'element-plus'
import {generateRandomNumbers} from "@/views/Home/index.ts";
import {generateRandomCancerTypes} from "@/views/Home/index可用";
import XEUtils from "xe-utils";

const formLoading = ref(false)
/* =============== 响应式数据 =============== */
const workbook   = ref(null)          // 整个 Excel 工作簿
const sheets     = ref({})            // { SheetName: { columns:[...], data:[...] } }
const activeName = ref('')            // 当前激活的页签名
const fileName = ref('')
/* =============== 1. 读取所有 Sheet =============== */
/* =============== 1. 读取所有 Sheet（跳过全空行） =============== */
function handleImport(e) {
    const file = e.target.files?.[0]
    fileName.value = file.name
    if (!file) return

    const ext = file.name.split('.').pop().toLowerCase()
    if (!['xlsx', 'xls', 'csv'].includes(ext)) {
        ElMessage.error('仅支持 .xlsx / .xls / .csv')
        return
    }

    const reader = new FileReader()
    reader.onload = (evt) => {
        try {
            const wb = XLSX.read(evt.target.result, { type: 'binary' })
            workbook.value = wb

            const temp = {}
            wb.SheetNames.forEach(name => {
                const ws = wb.Sheets[name]
                const json = XLSX.utils.sheet_to_json(ws, { header: 1 })
                if (!json.length) return

                const [headers, ...rows] = json

                /* 过滤：只要有一列有值就保留，否则跳过 */
                const validRows = rows.filter(r => r.some(v => v !== null && v !== ''))

                temp[name] = {
                    columns: headers,
                    data: validRows.map(r => {
                        const row = {}
                        headers.forEach((h, i) => (row[h] = r[i] ?? ''))
                        return row
                    })
                }
            })
            // console.log(temp,JSON.stringify(temp))
            sheets.value = temp
            activeName.value = wb.SheetNames[0] || ''
            ElMessage.success(`已加载 ${wb.SheetNames.length} 个 Sheet，共 ${Object.values(temp).reduce((s, i) => s + i.data.length, 0)} 行`)
        } catch (err) {
            ElMessage.error('解析失败：' + err.message)
        }
    }
    reader.readAsBinaryString(file)
    e.target.value = ''
}
/* =============== 2. 导出所有 Sheet（修复 blob 报错） =============== */
function handleExport() {
    if (!workbook.value) {
        ElMessage.warning('请先导入文件')
        return
    }

    /* 用 workbook.value 做模板，把改动写回每个工作表 */
    const wb = XLSX.utils.book_new()
    Object.entries(sheets.value).forEach(([name, { columns, data }]) => {
        const ws = XLSX.utils.json_to_sheet(data, { header: columns })
        XLSX.utils.book_append_sheet(wb, ws, name)
    })

    /* 生成 buffer，再用 file-saver 下载 */
    const buf = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
    saveAs(
        new Blob([buf], { type: 'application/octet-stream' }),
        `${fileName.value}.xlsx`
    )
}

const handleCreate = () => {
    formLoading.value = true
    Object.entries(sheets.value).forEach(([sheetName, { columns, data }]) => {
        columns.forEach(col => {
            // 取该列前 3 行（索引 0,1,2）
            const top3 = data.slice(0, 3).map(row => row[col])

            const top1 = data.slice(0, 1).map(row => row[col])
            // 只要有一个非空值
            const isAllNonEmpty = top3.every(v => v !== null && v !== '' && v !== undefined);
            if (isAllNonEmpty && top3.length === 3) {
                doSomething(sheetName,col)
            }
            if (top1[0] && `${top1[0]}`.indexOf('maxParams') !== -1) {
                doMaxParams(sheetName,col)
            }
        })
    })
    formLoading.value = false
}
function doSomething(sheetName,col) {
    /* 生成示例数据：按照已有行数*0.9 的均值 */
    // const avg =
    //     sheets.value['对照组'].data
    //         .slice(0, 3)
    //         .reduce((sum, r) => sum + Number(r[col] || 0), 0) / 3
    // const newVals = Array.from({ length: 5 }, (_, i) => (avg + i).toFixed(2))
    const avg =
            sheets.value[sheetName].data.slice(0, 4)
    let form = {
        count: avg[0][col],
        targetMean:  avg[1][col],
        targetStdDev:  avg[2][col],
        decimalPlaces: avg[3][col] || 0,
    }
    let arr = generateRandomNumbers(form)
    insertAfterRow3(sheetName, col, arr)
}
function doMaxParams(sheetName,col) {
    /* 生成示例数据：按照已有行数*0.9 的均值 */
    // const avg =
    //     sheets.value['对照组'].data
    //         .slice(0, 3)
    //         .reduce((sum, r) => sum + Number(r[col] || 0), 0) / 3
    // const newVals = Array.from({ length: 5 }, (_, i) => (avg + i).toFixed(2))
    const avg =
        sheets.value[sheetName].data.slice(0, 1)
    let obj = JSON.parse(avg[0][col])
    console.log(obj)
    let map = obj.arr.map(j => {
        return Array(j.count).fill(j.name)
    })
    let arr = generateRandomCancerTypes(XEUtils.flatten(map))
    // let form = {
    //     count: avg[0][col],
    //     targetMean:  avg[1][col],
    //     targetStdDev:  avg[2][col],
    //     decimalPlaces: avg[3][col] || 0,
    // }
    // let arr = generateRandomNumbers(form)
    insertAfterRow3(sheetName, col, arr)
}
/**
 * 把新数据插入指定列的“第 4 行及以后”
 * @param sheetName 工作表名
 * @param col       列名
 * @param newValues 待插入的数据数组
 */
function insertAfterRow3(
    sheetName,
    col,
    newValues
) {
    const sheet = sheets.value[sheetName]
    if (!sheet) return

    const { data } = sheet

    /* 1. 确保至少有 4 行（索引 0,1,2,3） */
    while (data.length < 5) {
        data.push(
            Object.fromEntries(sheet.columns.map(c => [c, '']))
        )
    }
    /* 2. 从第 4 行开始（索引 3）依次写入 newValues */
    newValues.forEach((val, idx) => {
        const rowIndex = 4 + idx
        // 如果还没到这一行，先补空行
        if (!data[rowIndex]) {
            data[rowIndex] = Object.fromEntries(sheet.columns.map(c => [c, '']))
        }
        data[rowIndex][col] = val
    })
    console.log(`已向工作表“${sheetName}”列“${col}”第 4 行起写入 ${newValues.length} 条数据`)
    // /* 3. 提示（可选） */
    ElMessage.success(
        `已向工作表“${sheetName}”列“${col}”第 4 行起写入 ${newValues.length} 条数据`
    )
    // ElMessage.success(
    //     `已向工作表“${sheetName}”列“${col}”第 4 行起写入 ${newValues.length} 条数据`
    // )
}
const copyToClipboard = () => {
    let text = "{\"type\":\"maxParams\",\"arr\":[{\"name\":\"女\",\"count\":18},{\"name\":\"男\",\"count\":20}]}"
    navigator.clipboard.writeText(text).then(() => {
        ElMessage.success(
            `复制成功`
        )
    })
}
</script>